import * as THREE from '../../../../modules/three/three.module.js';
import EditAction from "./EditAction.js";

export default class EditRecord extends THREE.EventDispatcher {
  _modified = false
  maximumStackLen = 100
  /**
   * @see EditAction
   * @type {EditAction[]}
   */
  stackUndo = []
  /**
   * @type {EditAction[]}
   */
  stackRedo = []

  clearAll() {
    this.stackUndo.length = 0
    this.stackRedo.length = 0
    this._modified = false
  }

  addAction(undoType, context) {
    this.stackRedo.length = 0
    const action = new EditAction(undoType, context)
    this.stackUndo.push(action)
    if (this.stackUndo.length > this.maximumStackLen) {
      this.stackUndo.shift()
    }
    this._modified = true
  }

  addOrUpdateAction(undoType, context) {
    let latestAction
    if (this.stackUndo.length > 0) {
      latestAction = this.stackUndo[this.stackUndo.length - 1]
    }

    if (latestAction && latestAction.undoType === undoType && latestAction.context.mesh === context.mesh) {
      latestAction.context.colorNew = context.colorNew
    } else {
      this.addAction(undoType, context)
    }
  }

  undoAction() {
    if (this.stackUndo.length === 0) {
      return
    }
    const action = this.stackUndo.pop()
    this.stackRedo.push(action)
    action.undo()
  }

  redoAction() {
    if (this.stackRedo.length === 0) {
      return
    }
    const action = this.stackRedo.pop()
    this.stackUndo.push(action)
    action.redo()
  }
}
